package main

import (
	"crypto/sha256"
	"encoding/hex"
)

// MerkleNode 表示默克尔树的节点
type MerkleNode struct {
	Hash     []byte
	Children []*MerkleNode
}

// NewLeafNode 创建一个新的叶子节点
func NewLeafNode(data []byte) *MerkleNode {
	hash := sha256.Sum256(data)
	return &MerkleNode{Hash: hash[:]}
}

// NewParentNode 创建一个新的父节点
func NewParentNode(left, right *MerkleNode) *MerkleNode {
	hash := sha256.Sum256(append(left.Hash, right.Hash...))
	return &MerkleNode{Hash: hash[:], Children: []*MerkleNode{left, right}}
}

// BuildMerkleTree 构建默克尔树
func BuildMerkleTree(data [][]byte) *MerkleNode {
	if len(data) == 0 {
		return nil
	}
	var nodes []*MerkleNode
	for _, d := range data {
		nodes = append(nodes, NewLeafNode(d))
	}
	for len(nodes) > 1 {
		var newNodes []*MerkleNode
		for i := 0; i < len(nodes); i += 2 {
			if i+1 < len(nodes) {
				newNodes = append(newNodes, NewParentNode(nodes[i], nodes[i+1]))
			} else {
				// 奇数个数据，复制最后一个节点
				newNodes = append(newNodes, NewParentNode(nodes[i], nodes[i]))
			}
		}
		nodes = newNodes
	}
	return nodes[0]
}

func main() {
	// 示例数据
	data := [][]byte{[]byte("block1"), []byte("block2"), []byte("block3")}

	// 构建默克尔树
	merkleTree := BuildMerkleTree(data)

	// 打印根节点的哈希值
	println("Merkle Root Hash:", hex.EncodeToString(merkleTree.Hash))
}
